
import 'dart:async';
import 'dart:convert';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/terminal_num_update_event.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_index_service.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/index/bean/index_top_info_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/new_terminal_list_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/click_back_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import 'media_settings_page.dart';

///播放天数页面
class MediaPlayTimePage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "MediaPlayTimePage";

  ///返回结果map 返回日期的key
  static const String RESULT_START_DAY = "result_start_day";
  static const String RESULT_END_DAY = "result_end_day";
  static const String RESULT_START_DAY_STR = "result_start_day_str";
  static const String RESULT_END_DAY_STR = "result_end_day_str";

  final DateTime startDay;
  final DateTime endDay;
  ///没有选择终端时，此时去添加终端，完成后需要跳转到设置时间页面
  final bool setTimeFlag;
  final String picid;
  final String hsns;
  const MediaPlayTimePage({Key key,this.startDay, this.endDay, this.setTimeFlag, this.picid, this.hsns}):super(key: key);

  @override
  _MediaPlayTimePageState createState() => _MediaPlayTimePageState();

  ///跳转方法
  static Future<Map<String, dynamic>> navigatorPush(
      BuildContext context, {DateTime startDay, DateTime endDay, bool setTimeFlag, String picid, String hsns}) {
    return RouterUtils.routeForFutureResult(
      context, MediaPlayTimePage(
      setTimeFlag: setTimeFlag,
      startDay: startDay,
      endDay: endDay,
      picid: picid,
      hsns: hsns,
    ),
      routeName: MediaPlayTimePage.ROUTER,
    );
  }
}

class _MediaPlayTimePageState extends BaseState<MediaPlayTimePage>{

  List<String> _timeList;
  int _selectIndex;
  String startDayStr = "";
  String endDayStr = "";
  String permanentDayStr = "";
  DateTime startDay;
  DateTime endDay;
  DateTime permanentDay;
  String interval = "";
  NewTerminalListViewModel _viewModel;
  int _allTerminalSize = 0;
  StreamSubscription _terminalNumRefreshSubscription;
  @override
  void initState() {
    super.initState();
    _timeList = new List();
    _timeList.add("1天");
    _timeList.add("7天");
    _timeList.add("15天");
    _timeList.add("30天");
    _timeList.add("45天");
    // _timeList.add("永久");
    _selectIndex = _timeList.indexOf("15天");
    interval = "15天";
    startDay = widget.startDay;
    if(widget?.endDay != null){
      endDay = widget?.endDay;
      interval = (((endDay.millisecondsSinceEpoch - startDay.millisecondsSinceEpoch)~/(1000*3600*24)) + 1).toString() + "天";
      if(_timeList.contains(interval)){
        _selectIndex = _timeList.indexOf(interval);
        interval = _timeList[_selectIndex];
      }else{
        _selectIndex = -1;
      }
    }else{
      _selectIndex = 4;
    }

    startDayStr = DateUtil.getDateStrByDateTime(startDay, format: DateFormat.YEAR_MONTH_DAY);
    if(widget?.endDay != null){
      endDayStr = DateUtil.getDateStrByDateTime(endDay, format: DateFormat.YEAR_MONTH_DAY);
    }

    print("startDay:" + startDayStr);
    // print("endDay:" + endDayStr??"永久");
    print("endDay:" + endDayStr??"");
    _viewModel = NewTerminalListViewModel(this);
    ///获取缓存数据
    String cacheKey = MediaSettingsPage.INDEX_TOP_INFO_API + (UserRepository.getInstance().authId ?? "")
        + (UserRepository.getInstance().companyId ?? "");
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        setState(() {
          Map map = json.decode(jsonStr);
          IndexTopInfoResponseBean bean = IndexTopInfoResponseBean.fromMap(map);
          if(bean != null){
            if(bean.data != null
                && bean.data.bindTerminalList != null){
              _allTerminalSize = bean.data.bindTerminalList.length;
            }
          }
        });
      }
    });
    _terminalNumRefreshSubscription = VgEventBus.global.streamController.stream.listen((event) {
      if(event is TerminalNumRefreshEvent){
        _allTerminalSize = event?.num??0;
      }
    });
  }

  @override
  void dispose() {
    _terminalNumRefreshSubscription?.cancel();
    super.dispose();
  }

  int _getIntervalDays(){
    switch (_selectIndex){
      case 0:
        return 0;
        break;
      case 1:
        return 6;
        break;
      case 2:
        return 14;
        break;
      case 3:
        return 29;
        break;
      // case 4:
      //   return -1;
      //   break;
      case 4:
        return 44;
        break;
    }
    return 0;
  }

  int getIntervalDaysByStartEndDay(){
    if("9999-99-99" == endDayStr || "10007-06-0" == endDayStr || StringUtils.isEmpty(endDayStr)){
      return 9999;
    }
    return (((endDay.millisecondsSinceEpoch - startDay.millisecondsSinceEpoch)~/(1000*3600*24)));
  }

  void setPermanentDayShow(){
    //yyyy-MM-dd
    int endYear = int.parse(startDayStr.substring(0, 4)) + 10;
    permanentDayStr = endYear.toString() + startDayStr.substring(4, startDayStr.length);
    permanentDay = DateTime.parse(permanentDayStr);
  }

  void clearPermanentDaySHow(){
    permanentDayStr = "";
    permanentDay = null;
  }

  DateTime getMaxEndDay(){
    //yyyy-MM-dd
    int maxEndYear = int.parse(startDayStr.substring(0, 4)) + 10;
    String maxEndDayStr = maxEndYear.toString() + startDayStr.substring(4, startDayStr.length);
    return DateTime.parse(maxEndDayStr);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: Column(
        children: <Widget>[
          _toTopBarWidget(),
          _listWidget(),
          SizedBox(height: 10,),
          _toSelectTimeWidget(),
          SizedBox(height: 30,),
          _toConfirmWidget(),
        ],
      ),
    );
  }

  ///标题栏
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "播放天数",
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }
  ///图片展示栏
  Widget _listWidget(){
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: ListView.separated(
        padding: EdgeInsets.only(top: 0),
        shrinkWrap: true,
        itemBuilder: (BuildContext context, int index) {
          return _toListItemWidget(context, index);
        },
        separatorBuilder: (BuildContext context, int index){
          return _toSplitLineWidget();
        },
        itemCount: _timeList?.length??0,
      ),
    );
  }

  ///item
  Widget _toListItemWidget(BuildContext context, int index){
    return ClickBackgroundWidget(
      onTap: (){
        setState(() {
          _selectIndex = index;
          interval = _timeList[_selectIndex];
          if(_getIntervalDays() != -1){
            endDay = DateTime.fromMillisecondsSinceEpoch(startDay.millisecondsSinceEpoch
                + _getIntervalDays()*24*3600*1000);
          }else{
            endDay = DateTime.parse("9999-99-99");
          }
          startDayStr = DateUtil.getDateStrByDateTime(startDay, format: DateFormat.YEAR_MONTH_DAY);
          if(_getIntervalDays() != -1){
            endDayStr = DateUtil.getDateStrByDateTime(endDay, format: DateFormat.YEAR_MONTH_DAY);
          }else{
            endDayStr = "9999-99-99";
          }
        });
      },
      child: Container(
        height: 50,
        child: Row(
          children: <Widget>[
            SizedBox(width: 15,),
            Text(
              _timeList[index],
              style: TextStyle(
                color: _selectIndex == index
                    ?ThemeRepository.getInstance().getPrimaryColor_1890FF()
                    :ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                fontSize: 14,
              ),
            ),
            SizedBox(width: 4,),
            Visibility(
              visible: _selectIndex == index,
              child: Image.asset(
                "images/icon_select_time.png",
                width: 11.3,
                height: 7,
              ),
            ),
          ],
        ),
      ),
    );
  }


  ///分割线
  Widget _toSplitLineWidget() {
    return Container(
      height: 0.5,
      margin: const EdgeInsets.only(left: 15, right: 0),
      color: ThemeRepository.getInstance().getLineColor_3A3F50(),
    );
  }

  ///下滑线
  Widget _toUnderLineWidget() {
    return Container(
      height: 0.5,
      // margin: const EdgeInsets.only(left: 15, right: 15),
      color: ThemeRepository.getInstance().getLineColor_3A3F50(),
    );
  }

  ///时间选择
  Widget _toSelectTimeWidget(){
    return Row(
      children: <Widget>[
        Visibility(
          child: Expanded(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 15),
              child: Column(
                children: <Widget>[
                  _toTimeWidget(
                      "${DateUtil.formatZHDateTime(startDayStr + " ", DateFormat.ZH_MONTH_DAY, "")}${DateUtil.isToday(startDay.millisecondsSinceEpoch)?"(今天)":""}",
                  true),
                  _toUnderLineWidget(),
                ],
              ),
            ),
          ),
        ),
        Visibility(
          visible: getIntervalDaysByStartEndDay() !=0,
            child: Container(
              width: 33,
              child: Text(
                "至",
                style: TextStyle(
                  color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                  fontSize: 14,
                ),
              ),
            ),
        ),
        Visibility(
          visible: getIntervalDaysByStartEndDay() !=0,
          child: Expanded(
            child: Container(
              padding: EdgeInsets.only(right: 15),
              child: Column(
                children: <Widget>[
                  _toTimeWidget(
                    _getIntervalDays() == -1?"永久"
                      :"${DateUtil.formatZHDateTime(endDayStr + " ", DateFormat.ZH_MONTH_DAY, "")}${DateUtil.isToday(endDay.millisecondsSinceEpoch)?"(今天)":""}",
                  false),
                  _toUnderLineWidget(),
                ],
              ),
            ),
          ),
        ),
      ],

    );
  }

  ///日期显示
  Widget _toTimeWidget(String time, bool start){
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: (){
        start?_startDatePicker():_endDatePicker();
      },
      child: Container(
        height: 50,
        child: Row(
          children: <Widget>[
            Expanded(
              child:
                Container(
                  alignment: Alignment.center,
                  child: Text(
                    time,
                    style: TextStyle(
                      color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                      fontSize: 14,
                    ),
                  ),
                ),
            ),

               Container(
                 padding: EdgeInsets.only(top: 15, right: 15, bottom: 15),
                 // margin: EdgeInsets.only(right: 15),
                 child: Image.asset(
                  "images/icon_arrow_down.png",
                  width: 12,
              ),
               ),

          ],
        ),
      ),
    );
  }

  _startDatePicker(){
    return DatePicker.showDatePicker(
        context,
        pickerTheme: DateTimePickerTheme(
            showTitle: true,
            backgroundColor:
            ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
            confirm: Text('确定',
                style: TextStyle(
                  color:
                  ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                )),
            cancel: Text('取消',
                style: TextStyle(
                    color:
                    ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
            itemTextStyle: TextStyle(color: Colors.white)
          // backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        ),
        minDateTime: DateTime.parse(DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY)), //起始日期
        maxDateTime: getMaxEndDay(), //终止日期
        initialDateTime: startDay, //当前日期
        dateFormat: 'yyyy-MMMM-dd',  //显示
        locale: DateTimePickerLocale.zh_cn, //语言 默认DateTimePickerLocale.en_us// 格式
        onClose: () => print("----- onClose -----"),
        onCancel: () => print('onCancel'),
        onConfirm: (dateTime, List<int> index) { //确定的时候
          setState(() {
            if(_getIntervalDays() == 0){
              endDay = dateTime;
              endDayStr = DateUtil.getDateStrByDateTime(endDay, format: DateFormat.YEAR_MONTH_DAY);
            }
            if(endDay.millisecondsSinceEpoch < dateTime.millisecondsSinceEpoch){
              VgToastUtils.toast(context, "结束日期不能早于开始日期");
              return;
            }
            startDay = dateTime;
            startDayStr = DateUtil.getDateStrByDateTime(startDay, format: DateFormat.YEAR_MONTH_DAY);

              interval = (((endDay.millisecondsSinceEpoch - startDay.millisecondsSinceEpoch)~/(1000*3600*24)) + 1).toString() + "天";
              if("9999-99-99" == endDayStr){
                _selectIndex = 4;
              }else{
                if(_timeList.contains(interval)){
                  _selectIndex = _timeList.indexOf(interval);
                  interval = _timeList[_selectIndex];
                }else{
                  _selectIndex = -1;
                }
              }

            // if (_getIntervalDays() != null && _getIntervalDays() != -1){
            //   endDay = DateTime.fromMillisecondsSinceEpoch(startDay.millisecondsSinceEpoch
            //       + _getIntervalDays()*24*3600*1000);
            //   endDayStr = DateUtil.getDateStrByDateTime(endDay, format: DateFormat.YEAR_MONTH_DAY);
            //
            //   interval = (((endDay.millisecondsSinceEpoch - startDay.millisecondsSinceEpoch)~/(1000*3600*24)) + 1).toString() + "天";
            //   if(_timeList.contains(interval)){
            //     _selectIndex = _timeList.indexOf(interval);
            //     interval = _timeList[_selectIndex];
            //   }else{
            //     _selectIndex = -1;
            //   }
            // }

          });
        }
    );
  }

  _endDatePicker(){
    return DatePicker.showDatePicker(
        context,
        pickerTheme: DateTimePickerTheme(
            showTitle: true,
            backgroundColor:
            ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
            confirm: Text('确定',
                style: TextStyle(
                  color:
                  ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                )),
            cancel: Text('取消',
                style: TextStyle(
                    color:
                    ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
            itemTextStyle: TextStyle(color: Colors.white)
          // backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        ),
        minDateTime: DateTime.parse(startDayStr), //起始日期
        maxDateTime: getMaxEndDay(), //终止日期
        initialDateTime: _getIntervalDays() == -1?getMaxEndDay():endDay, //当前日期
        dateFormat: 'yyyy-MMMM-dd',  //显示
        locale: DateTimePickerLocale.zh_cn, //语言 默认DateTimePickerLocale.en_us// 格式
        onClose: () => print("----- onClose -----"),
        onCancel: () => print('onCancel'),
        onConfirm: (dateTime, List<int> index) { //确定的时候
          if(dateTime.millisecondsSinceEpoch < startDay.millisecondsSinceEpoch){
            VgToastUtils.toast(context, "结束日期不能早于开始日期");
            return;
          }
          setState(() {
            endDay = dateTime;
            endDayStr = DateUtil.getDateStrByDateTime(endDay, format: DateFormat.YEAR_MONTH_DAY);
            interval = ((endDay.millisecondsSinceEpoch - startDay.millisecondsSinceEpoch)~/(1000*3600*24) + 1).toString() + "天";
            if(_timeList.contains(interval)){
              _selectIndex = _timeList.indexOf(interval);
              interval = _timeList[_selectIndex];
            }else{
              _selectIndex = -1;
            }
          });
        }
    );
  }

  ///确定
  Widget _toConfirmWidget(){
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: true,
      height: 40,
      margin: const EdgeInsets.symmetric(horizontal: 15),
      unSelectBgColor: Color(0xFF3A3F50),
      selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectTextStyle: TextStyle(
        color: VgColors.INPUT_BG_COLOR,
        fontSize: 15,
      ),
      selectedTextStyle: TextStyle(
        color: Colors.white,
        fontSize: 15,
        // fontWeight: FontWeight.w600
      ),
      text: (_timeList.contains(interval) || "9999-99-99"==endDayStr)?"确定":"确定(${interval??""})",
      onTap: (){
        if(widget?.setTimeFlag??false){
          _viewModel.addMediaToTerminals(context,
              StringUtils.isEmpty(widget.hsns)?"00"
                  :((_allTerminalSize == widget.hsns.split(",").length)?"01":"00"),
              startDayStr, endDayStr, widget.hsns, widget?.picid, setTimeFlag: true);
        }else{
          RouterUtils.pop(context, result: {
            MediaPlayTimePage.RESULT_START_DAY: startDay,
            MediaPlayTimePage.RESULT_START_DAY_STR: startDayStr,
            MediaPlayTimePage.RESULT_END_DAY: (_getIntervalDays() == -1)?null:endDay,
            MediaPlayTimePage.RESULT_END_DAY_STR: (_getIntervalDays() == -1)?"9999-99-99":endDayStr,
          });
        }
      },
    );
  }

}